import { reactive, ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { useTagsViewStore } from "./tags-view"
import { useMqttStore } from "./mqtt"
import { useSettingsStore } from "./settings"
import { getToken, removeToken, setToken, removeAccessToken, setAccessToken } from "@/utils/token"
import { resetRouter } from "@/router"
import { loginApi, getUserInfoApi, loginTokenApi, userLoginOutApi } from "@/api/login"
import { type ILoginRequestData, IInfoData, ILoginTokenRequestData, ILoginParams, INode } from "@/api/login/types/login"
import routeSettings from "@/config/route"
import { ElMessage } from "element-plus"
import { useRouter } from "vue-router"
export const useUserStore = defineStore("user", () => {
  const is_signin = ref(1) // 0为从未登陆过 1为登陆并已修改过密码
  const token = ref<string>(getToken() || "")
  const roles = ref<string[]>([])
  const username = ref<string>("")
  const accessToken = ref<string>("")
  const userInfo = reactive<Partial<IInfoData>>({})
  const permissionRouter = ref<INode[]>([])
  const mqttStore = useMqttStore()
  const tagsViewStore = useTagsViewStore()
  const settingsStore = useSettingsStore()
  const router = useRouter()

  /** 登录 */
  const login = async ({ number, password }: ILoginParams) => {
    try {
      const params: ILoginTokenRequestData = {
        client_id: "20882088",
        secret: "nGk5R2wrnZqQ02bed29rjzax1QWRIu1O"
      }
      const resToken = await loginTokenApi(params)

      const { result: tokenResult, data: tokenData, return_message: tokenMessage } = resToken

      if (tokenResult === 200) {
        accessToken.value = tokenData.access_token
        // setToken(tokenData.access_token)
        setAccessToken(tokenData.access_token)
      } else {
        ElMessage.error(tokenMessage)
      }

      const loginParams: ILoginRequestData = {
        number,
        password,
        mode: "none",
        isFirst: 1
      }

      const res = await loginApi(loginParams)

      const { result: loginResult, return_message: loginMessage, data } = res
      if (loginResult !== 200) {
        removeToken()
        removeAccessToken()
        ElMessage.error(loginMessage)
      } else {
        token.value = data
        setToken(data)
        // 检验是否初次登录
        await getInfo(true)
      }
    } catch (error) {
      console.info(error)
    }
  }

  /** 获取用户详情 */
  const getInfo = async (isFirst: boolean) => {
    const userRes = await getUserInfoApi()
    // 初始化连接mqtt
    mqttStore.mqConnect()
    const { result, data, return_message } = userRes

    if (result === 200) {
      username.value = data.userinfo.user_name
      // 验证返回的 roles 是否为一个非空数组，否则塞入一个没有任何作用的默认角色，防止路由守卫逻辑进入无限循环
      // roles.value = data.roles?.length > 0 ? data.roles : routeSettings.defaultRoles
      Object.assign(userInfo, data.userinfo)
      is_signin.value = data.is_signin
      if (!isFirst) {
        roles.value = [...routeSettings.defaultRoles, "admin"]
      }
      permissionRouter.value = data.node
    } else {
      removeToken()
      removeAccessToken()
      ElMessage.error(return_message)
    }
  }

  // 跳到登录页
  const toLogin = () => {
    removeToken()
    removeAccessToken()
    router.push("/login")
  }

  /** 登出 */
  const logout = async () => {
    try {
      const res = await userLoginOutApi()
      const { result, return_message } = res
      if (result === 200) {
        router.push("/login")
        mqttStore.close && mqttStore.close()
        removeToken()
        removeAccessToken()
        roles.value = []
        userInfo.user_role = ""
        resetRouter()
        _resetTagsView()
      } else {
        ElMessage.error(return_message)
      }
    } catch (error) {
      console.info(error)
    }
  }

  // 激活页面
  const platformAuthExpired = () => {
    router.push("/expired")
  }

  // 刷新accessToken
  const doRefreshToken = async () => {
    const params: ILoginTokenRequestData = {
      client_id: "20882088",
      secret: "nGk5R2wrnZqQ02bed29rjzax1QWRIu1O"
    }
    const resToken = await loginTokenApi(params)
    setAccessToken(resToken.data.access_token)
  }

  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    roles.value = []
  }
  /** 重置 Visited Views 和 Cached Views */
  const _resetTagsView = () => {
    if (!settingsStore.cacheTagsView) {
      tagsViewStore.delAllVisitedViews()
      tagsViewStore.delAllCachedViews()
    }
  }

  const setSignin = () => {
    is_signin.value = 1
  }

  return {
    permissionRouter,
    token,
    roles,
    username,
    userInfo,
    accessToken,
    is_signin,
    login,
    setSignin,
    toLogin,
    getInfo,
    logout,
    resetToken,
    platformAuthExpired,
    doRefreshToken
  }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
